package com.xyu.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xyu.gulimall.product.entity.BrandEntity;
import com.xyu.gulimall.product.service.BrandService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyu.common.utils.PageUtils;
import com.xyu.common.utils.Query;

import com.xyu.gulimall.product.dao.CategoryBrandRelationDao;
import com.xyu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.xyu.gulimall.product.service.CategoryBrandRelationService;

import javax.annotation.Resource;

//品牌分类关联关系表 [商品与品牌关联关系]
@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Resource
    private CategoryBrandRelationDao relationDao;
    @Resource
    private BrandService brandService;
    //分页全部查询
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                //构造无查询条件，参数接收需要返回查询条件
                new QueryWrapper<CategoryBrandRelationEntity>()
        );
        return new PageUtils(page);
    }

    //更新
    @Override
    public void updateBrand(Long brandId, String name) {
        //创建商品关联关系实体类
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        //条件id
        categoryBrandRelationEntity.setBrandId(brandId);
        //更新name
        categoryBrandRelationEntity.setBrandName(name);
        //执行更新操作
        this.update(categoryBrandRelationEntity, new UpdateWrapper<CategoryBrandRelationEntity>()
                .eq("brand_id", brandId));

    }

    @Override
    public void UpdateCategory(Long catId, String name) {
        System.out.println(catId + "\t" + name);
        this.baseMapper.updateCategory(catId, name);
    }

    //、获取分类关联的品牌
    @Override
    public List<BrandEntity> getBrandId(Long catId) {
        //查询关联关系表
        List<CategoryBrandRelationEntity> categoryId = relationDao.selectList(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId));
        //通过流获取分类的id然后去品牌表查找对应的记录
        List<BrandEntity> collect = categoryId.stream().map(item -> {
            Long brandId = item.getBrandId();
            //根据关联关系表的分类id去品牌表查询
            return brandService.getById(brandId);
        }).collect(Collectors.toList());
        return collect;
    }
}
